package cn.xiaopengstack.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author jiangyangang
 */
@Slf4j
public class RestClientFilter implements ClientHttpRequestInterceptor {

    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
        // 打印发送给大模型的消息
        log.info("=== 发送给大模型的请求 ===");
        log.info("URL:{}", request.getURI());
        log.info("Headers:{}", request.getHeaders());
        log.info("Body:{}", new String(body, StandardCharsets.UTF_8));

        // 执行请求并获取响应
        ClientHttpResponse response = execution.execute(request, body);

        CachedClientHttpResponse cachedClientHttpResponse = new CachedClientHttpResponse(response);

        log.info("=== 大模型的响应 ===");
        log.info("Status:{}", response.getStatusCode());
        log.info("Headers:{}", response.getHeaders());
        log.info("Body:{}", new String(cachedClientHttpResponse.getBody().readAllBytes(), StandardCharsets.UTF_8));

        return cachedClientHttpResponse;
    }
}
